

package com.zlp.spring.one.annotation;


import com.zlp.spring.one.config.BeanDefinition;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自动义 ApplicationContext 容器
 *
 * @date: 2021/12/29 11:24
 */
public class ZlpAnnotationConfigApplicationContext {

    protected Class objClass;

    private static final String SINGLETON = "singleton";

    /**
     * 单例 bean 容器
     */
    private static ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    /**
     * beanDefinition 容器
     */
    private static ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private static List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public ZlpAnnotationConfigApplicationContext(Class objClass) {

        this.objClass = objClass;
        // 扫包
        componentScan(objClass);
        for (Map.Entry<String, BeanDefinition> beanDefinitionEntry : beanDefinitionMap.entrySet()) {
            BeanDefinition beanDefinition = beanDefinitionEntry.getValue();
            if (Objects.equals(beanDefinition.getScope(), SINGLETON)) {
                Object obj = createBean(beanDefinition, beanDefinitionEntry.getKey());
                singletonObjects.put(beanDefinitionEntry.getKey(), obj);
            }
        }
    }


    /**
     * 创建 BeanDefinition
     *
     * @param beanDefinition
     * @date: 2021/12/29 14:13
     */
    private Object createBean(BeanDefinition beanDefinition, String beanName) {

        Class clazz = beanDefinition.getClazz();
        Object instance = null;
        try {
            instance = clazz.getDeclaredConstructor().newInstance();
            // 依赖注入
            Field[] declaredFields = clazz.getDeclaredFields();
            // 遍历所有的属性
            if (Objects.nonNull(declaredFields)) {
                for (Field declaredField : declaredFields) {
                    if (declaredField.isAnnotationPresent(Autowired.class)) {
                        Object object = getBean(declaredField.getName());
                        declaredField.setAccessible(true);
                        declaredField.set(instance, object);
                    }
                }
            }

            // aware 回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            // postProcessBeforeInitialization
            if (!CollectionUtils.isEmpty(beanPostProcessorList)) {
                for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                    instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
                }
            }
            // 初始化
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            // postProcessAfterInitialization
            if (!CollectionUtils.isEmpty(beanPostProcessorList)) {
                for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                    instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }

    private void componentScan(Class objClass) {
        // 获取扫描包路径
        ComponentScan componentScan = (ComponentScan) objClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScan.value();
        System.out.println(path);
        // 类反射机制加载
        ClassLoader classLoader = ZlpAnnotationConfigApplicationContext.class.getClassLoader();
        String classPath = path.replace(".", "/");
        URL resource = classLoader.getResource(classPath);
        // 获取扫描包绝对路径地址
        File files = new File(resource.getPath());
        if (files.isDirectory()) {
            // 获取扫描包路径下面 class 集合
            File[] listFiles = files.listFiles();
            for (File file : listFiles) {
                if (file.isDirectory()) {
                    for (File file1 : file.listFiles()) {
                        parseClazz(classLoader, file1);
                    }
                }
                parseClazz(classLoader, file);
            }
        }
    }

    private void parseClazz(ClassLoader classLoader, File file) {
        String absolutePath = file.getAbsolutePath();
        if (absolutePath.contains(".class") && absolutePath.contains("com") ) {
            String calssName = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
            calssName = calssName.replace("\\", ".");
            try {
                Class<?> clazz = classLoader.loadClass(calssName);
                if (clazz.isAnnotationPresent(Component.class)) {
                    Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                    // BeanPostProcessor
                    if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                        BeanPostProcessor beanPostProcessor = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                        beanPostProcessorList.add(beanPostProcessor);
                    }
                    // 设置 BeanDefinition
                    BeanDefinition beanDefinition = new BeanDefinition();
                    beanDefinition.setClazz(clazz);
                    // 解析类，判断当前Bean 是 singleton 或是 prototype
                    if (clazz.isAnnotationPresent(Scope.class)) {
                        Scope scopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                        beanDefinition.setScope(scopeAnnotation.value());
                    } else {
                        beanDefinition.setScope(SINGLETON);
                    }
                    beanDefinitionMap.put(componentAnnotation.value(), beanDefinition);
                }

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public Object getBean(String beanName) {

        if (beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (Objects.equals(beanDefinition.getScope(), SINGLETON)) {
                if (Objects.isNull(singletonObjects.get(beanName))) {
                    return createBean(beanDefinition, beanName);
                }
                return singletonObjects.get(beanName);
            } else {
                return createBean(beanDefinition, beanName);
            }
        } else {
            throw new NullPointerException("Get Bean does not exist");
        }
    }


}
